package org.wu.spring.orm.integration.compare.infrastructure.persistence.eloquent;

import com.easy.query.api4j.client.EasyQuery;
import com.easy.query.core.api.pagination.EasyPageResult;
import gaarason.database.appointment.Paginate;
import gaarason.database.contract.eloquent.Record;
import gaarason.database.contract.eloquent.RecordList;
import gaarason.database.eloquent.GeneralModel;
import gaarason.database.query.MySqlBuilder;
import jakarta.annotation.Resource;
import org.sagacity.sqltoy.model.EntityQuery;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.wu.framework.core.utils.ObjectUtils;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;
import org.wu.spring.orm.integration.compare.domain.model.sys.user.ORMComparisonRepository;
import org.wu.spring.orm.integration.compare.domain.model.sys.user.SysUser;
import org.wu.spring.orm.integration.compare.infrastructure.converter.SysUserConverter;
import org.wu.spring.orm.integration.compare.infrastructure.entity.SysUserDO;
import org.wu.spring.orm.integration.compare.infrastructure.mapper.eloquent.EloquentMapper;
import org.wu.spring.orm.integration.compare.infrastructure.persistence.SysUserRepositoryAbstractRecord;
import org.wu.spring.orm.integration.compare.infrastructure.persistence.enums.Orm;
import org.wu.spring.orm.integration.compare.infrastructure.persistence.enums.Type;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * describe sys_user
 *
 * @author Jia wei Wu
 * @date 2024/02/28 11:27 上午
 * @see org.wu.framework.lazy.orm.core.persistence.reverse.lazy.ddd.DefaultDDDLazyInfrastructurePersistence
 **/
@Component("Eloquent")
public class EloquentComparisonRepository extends SysUserRepositoryAbstractRecord implements ORMComparisonRepository {


    @Resource
    GeneralModel generalModel;

    @Resource
    EloquentMapper eloquentMapper;

    /**
     * describe 新增
     *
     * @param sysUser 新增
     * @return {@link Result<SysUser>} 新增后领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> story(SysUser sysUser) throws Exception {
        boolean success = true;
        super.resetTestTableRecords();
        LocalDateTime startTime = LocalDateTime.now();
        try {
            SysUserDO sysUserDO = SysUserConverter.INSTANCE.fromSysUser(sysUser);
            eloquentMapper.newQuery().from("sys_user").value(sysUserDO).upsert("id");
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }

        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.Eloquent, Type.story, startTime, endTime, success);
        return ResultFactory.successOf();
    }

    /**
     * describe 批量新增
     *
     * @param sysUserList 批量新增
     * @return {@link Result<List<SysUser>>} 新增后领域对象集合
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<List<SysUser>> batchStory(List<SysUser> sysUserList) throws Exception {
        boolean success = true;
        super.resetTestTableRecords();
        LocalDateTime startTime = LocalDateTime.now();
        try {
            List<SysUserDO> sysUserDOList = sysUserList.stream().map(SysUserConverter.INSTANCE::fromSysUser).collect(Collectors.toList());
            eloquentMapper.newQuery().from("sys_user").values(sysUserDOList).upsert("id");
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }
        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.Eloquent, Type.batchStory, startTime, endTime, sysUserList.size(), success);
        return ResultFactory.successOf();
    }

    /**
     * describe 查询单个
     *
     * @param sysUser 查询单个
     * @return {@link Result<SysUser>} 领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> findOne(SysUser sysUser) throws Exception {
        boolean success = true;
        super.findOne(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        SysUser one = null;
        try {
            // .... 将条件逐个添加
            Record<SysUserDO, Long> first = eloquentMapper
                    .newQuery()
                    .from("sys_user")
                    .table("sys_user")
                    .where("id", sysUser.getId())
                    .where("is_deleted", sysUser.getIsDeleted())
                    .whereLike("username", sysUser.getUsername())
                    .first();
            SysUserDO entity = first.getEntity();
            one = SysUserConverter.INSTANCE.toSysUser(entity);

        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.Eloquent, Type.findOne, startTime, endTime, success);
        return ResultFactory.successOf(one);
    }

    /**
     * describe 查询多个
     *
     * @param sysUser 查询多个
     * @return {@link Result<List<SysUser>>} 领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<List<SysUser>> findList(SysUser sysUser) throws Exception {
        boolean success = true;
        super.findList(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        List<SysUser> sysUserList = new ArrayList<>();
        try {
            RecordList<SysUserDO, Long> records = eloquentMapper.newQuery()
                    .from("sys_user")
                    .table("sys_user")
                    .when(ObjectUtils.isNotEmpty(sysUser.getId()), builder -> builder.where("id", sysUser.getId()))
                    .when(ObjectUtils.isNotEmpty(sysUser.getIsDeleted()), builder -> builder.where("is_deleted", sysUser.getIsDeleted()))
                    .when(ObjectUtils.isNotEmpty(sysUser.getUsername()), builder -> builder.whereLike("username", sysUser.getUsername()))
                    .get();


            sysUserList = records.stream().map(sysUserDOLongRecord -> {
                SysUserDO entity = sysUserDOLongRecord.getEntity();
                return SysUserConverter.INSTANCE.toSysUser(entity);
            }).toList();

        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.Eloquent, Type.findList, startTime, endTime, success);

        return ResultFactory.successOf(sysUserList);
    }

    /**
     * describe 分页查询多个
     *
     * @param size    当前页数
     * @param current 当前页
     * @param sysUser 分页查询多个
     * @return {@link Result<LazyPage<SysUser>>} 分页领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<LazyPage<SysUser>> findPage(int size, int current, SysUser sysUser) throws Exception {
        boolean success = true;
        super.findPage(size, current, sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        LazyPage<SysUser> lazyPage = new LazyPage<>(current, size);
        try {

            Paginate<SysUserDO> paginate = eloquentMapper.newQuery()
                    .from("sys_user")
                    .table("sys_user")
                    .when(ObjectUtils.isNotEmpty(sysUser.getId()), builder -> builder.where("id", sysUser.getId()))
                    .when(ObjectUtils.isNotEmpty(sysUser.getIsDeleted()), builder -> builder.where("is_deleted", sysUser.getIsDeleted()))
                    .when(ObjectUtils.isNotEmpty(sysUser.getUsername()), builder -> builder.where("username", sysUser.getUsername()))
                    .paginate(current, size);


            List<SysUser> list = paginate.getItemList().stream().map(SysUserConverter.INSTANCE::toSysUser).toList();

            // .... 将条件逐个添加

            lazyPage.setTotal(paginate.getTotal());
            lazyPage.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.Eloquent, Type.findPage, startTime, endTime, size, success);
        return ResultFactory.successOf(lazyPage);
    }

    /**
     * describe 删除
     *
     * @param sysUser 删除
     * @return {@link Result<SysUser>}
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<SysUser> remove(SysUser sysUser) throws Exception {
        boolean success = true;
        super.remove(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        try {
            eloquentMapper.newQuery()
                    .from("sys_user")
                    .table("sys_user")
                    .when(ObjectUtils.isNotEmpty(sysUser.getId()), builder -> builder.where("id", sysUser.getId()))
                    .when(ObjectUtils.isNotEmpty(sysUser.getIsDeleted()), builder -> builder.where("is_deleted", sysUser.getIsDeleted()))
                    .when(ObjectUtils.isNotEmpty(sysUser.getUsername()), builder -> builder.where("username", sysUser.getUsername()))
                    .forceDelete();
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.Eloquent, Type.remove, startTime, endTime, success);
        return ResultFactory.successOf();
    }

    /**
     * describe 是否存在
     *
     * @param sysUser 领域对象
     * @return {@link Result<Boolean>} 是否存在 true 存在，false 不存在
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/

    @Override
    public Result<Boolean> exists(SysUser sysUser) throws Exception {
        boolean success = true;
        super.exists(sysUser);
        LocalDateTime startTime = LocalDateTime.now();
        boolean any = false;
        try {
            Long count = eloquentMapper.newQuery()
                    .from("sys_user")
                    .table("sys_user")
                    .when(ObjectUtils.isNotEmpty(sysUser.getId()), builder -> builder.where("id", sysUser.getId()))
                    .when(ObjectUtils.isNotEmpty(sysUser.getIsDeleted()), builder -> builder.where("is_deleted", sysUser.getIsDeleted()))
                    .when(ObjectUtils.isNotEmpty(sysUser.getUsername()), builder -> builder.where("username", sysUser.getUsername()))
                    .count();
            any = count > 0;
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }


        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(Orm.Eloquent, Type.exists, startTime, endTime, success);
        return ResultFactory.successOf(any);
    }

}